# -*- coding: utf-8 -*-
# Author   : ZhangQing
# Time     : 2025-08-05 23:05
# File     : logger.py
# Project  : codebuddy_craft
# Desc     : 功能完善的日志系统

# backend/utils/log_utils.py
"""
日志工具函数 🛠️

提供常用的日志记录工具函数
"""

import os
import sys
import logging
import logging.handlers
from pathlib import Path
from typing import Optional, Dict, Any, Union
import logging
import functools
from typing import Any, Dict, Optional, Callable
from datetime import datetime
import asyncio

try:
    import colorlog
    HAS_COLORLOG = True
except ImportError:
    HAS_COLORLOG = False

from backend.core.settings import Settings

# from .logger import get_logger, get_security_logger, get_performance_logger


class ColoredFormatter(logging.Formatter):
    """彩色日志格式化器 🌈"""

    # 颜色代码
    COLORS = {
        'DEBUG': '\033[36m',  # 青色
        'INFO': '\033[32m',  # 绿色
        'WARNING': '\033[33m',  # 黄色
        'ERROR': '\033[31m',  # 红色
        'CRITICAL': '\033[41m',  # 红色背景
        'RESET': '\033[0m'  # 重置
    }

    def format(self, record):
        """格式化日志记录"""
        if HAS_COLORLOG or hasattr(sys.stderr, 'isatty') and sys.stderr.isatty():
            # 添加颜色
            color = self.COLORS.get(record.levelname, self.COLORS['RESET'])
            record.levelname = f"{color}{record.levelname}{self.COLORS['RESET']}"

        return super().format(record)


class StructuredFormatter(logging.Formatter):
    """结构化日志格式化器 📊"""

    def format(self, record):
        """格式化为结构化JSON"""
        import json

        log_data = {
            'timestamp': datetime.fromtimestamp(record.created).isoformat(),
            'level': record.levelname,
            'logger': record.name,
            'message': record.getMessage(),
            'module': record.module,
            'function': record.funcName,
            'line': record.lineno
        }

        # 添加额外字段
        if hasattr(record, 'user_id'):
            log_data['user_id'] = record.user_id
        if hasattr(record, 'request_id'):
            log_data['request_id'] = record.request_id
        if hasattr(record, 'ip_address'):
            log_data['ip_address'] = record.ip_address
        if hasattr(record, 'event_type'):
            log_data['event_type'] = record.event_type

        # 异常信息
        if record.exc_info:
            log_data['exception'] = self.formatException(record.exc_info)

        return json.dumps(log_data, ensure_ascii=False)


class RequestIDFilter(logging.Filter):
    """请求ID过滤器 🔍"""

    def filter(self, record):
        """添加请求ID到日志记录"""
        # 尝试从上下文获取请求ID
        try:
            from contextvars import ContextVar
            request_id_var: ContextVar = ContextVar('request_id', default=None)
            record.request_id = request_id_var.get()
        except:
            record.request_id = None

        return True


class SQLAlchemyFilter(logging.Filter):
    """SQLAlchemy日志过滤器 🗄️"""

    def filter(self, record):
        """过滤SQLAlchemy的重复日志"""
        # 过滤掉一些重复的SQL日志
        if record.name.startswith('sqlalchemy.engine'):
            # 只记录错误和警告
            return record.levelno >= logging.WARNING
        return True


def setup_logging(settings: Settings) -> None:
    """设置日志系统 📝

    Args:
        settings: 应用配置
    """

    # 清除现有的处理器
    root_logger = logging.getLogger()
    for handler in root_logger.handlers[:]:
        root_logger.removeHandler(handler)

    # 设置根日志级别
    root_logger.setLevel(getattr(logging, settings.LOG_LEVEL.upper()))

    # 创建日志目录
    if settings.LOG_FILE:
        log_path = Path(settings.LOG_FILE)
        log_path.parent.mkdir(parents=True, exist_ok=True)

    # 设置日志格式
    console_format = get_console_format(settings)
    file_format = get_file_format(settings)

    # 控制台处理器
    console_handler = create_console_handler(console_format, settings)
    if console_handler:
        root_logger.addHandler(console_handler)

    # 文件处理器
    if settings.LOG_FILE:
        file_handler = create_file_handler(settings.LOG_FILE, file_format, settings)
        if file_handler:
            root_logger.addHandler(file_handler)

        # 错误日志文件
        error_handler = create_error_handler(settings.LOG_FILE, file_format, settings)
        if error_handler:
            root_logger.addHandler(error_handler)

    # 配置特定日志记录器
    configure_loggers(settings)

    # 记录启动信息
    logger = logging.getLogger(__name__)
    logger.info(f"🚀 日志系统已初始化 (级别: {settings.LOG_LEVEL})")

    if settings.LOG_FILE:
        logger.info(f"📁 日志文件: {settings.LOG_FILE}")


def get_console_format(settings: Settings) -> str:
    """获取控制台日志格式 🖥️"""
    if settings.is_development:
        return "%(asctime)s | %(levelname)-8s | %(name)-25s | %(message)s"
    else:
        return "%(asctime)s | %(levelname)-8s | %(message)s"


def get_file_format(settings: Settings) -> str:
    """获取文件日志格式 📄"""
    return "%(asctime)s | %(levelname)-8s | %(name)-30s | %(funcName)-20s:%(lineno)-3d | %(message)s"


def create_console_handler(format_str: str, settings: Settings) -> Optional[logging.Handler]:
    """创建控制台处理器 🖥️"""
    try:
        handler = logging.StreamHandler(sys.stdout)
        handler.setLevel(getattr(logging, settings.LOG_LEVEL.upper()))

        # 使用彩色格式化器
        if HAS_COLORLOG and settings.is_development:
            formatter = colorlog.ColoredFormatter(
                '%(log_color)s%(asctime)s | %(levelname)-8s%(reset)s | '
                '%(blue)s%(name)-25s%(reset)s | %(message)s',
                datefmt='%H:%M:%S',
                log_colors={
                    'DEBUG': 'cyan',
                    'INFO': 'green',
                    'WARNING': 'yellow',
                    'ERROR': 'red',
                    'CRITICAL': 'red,bg_white',
                }
            )
        else:
            formatter = ColoredFormatter(
                format_str,
                datefmt='%Y-%m-%d %H:%M:%S'
            )

        handler.setFormatter(formatter)

        # 添加过滤器
        handler.addFilter(RequestIDFilter())

        return handler

    except Exception as e:
        print(f"❌ 创建控制台日志处理器失败: {e}")
        return None


def create_file_handler(log_file: str, format_str: str, settings: Settings) -> Optional[logging.Handler]:
    """创建文件处理器 📄"""
    try:
        # 使用轮转文件处理器
        handler = logging.handlers.TimedRotatingFileHandler(
            filename=log_file,
            when='midnight',  # 每天轮转
            interval=1,
            backupCount=30,  # 保留30天
            encoding='utf-8',
            delay=True
        )

        handler.setLevel(logging.DEBUG)

        # 根据环境选择格式化器
        if settings.is_production:
            formatter = StructuredFormatter()
        else:
            formatter = logging.Formatter(
                format_str,
                datefmt='%Y-%m-%d %H:%M:%S'
            )

        handler.setFormatter(formatter)

        # 添加过滤器
        handler.addFilter(RequestIDFilter())

        return handler

    except Exception as e:
        print(f"❌ 创建文件日志处理器失败: {e}")
        return None


def create_error_handler(log_file: str, format_str: str, settings: Settings) -> Optional[logging.Handler]:
    """创建错误日志处理器 ❌"""
    try:
        # 错误日志文件路径
        error_log_file = log_file.replace('.log', '_error.log')

        handler = logging.handlers.TimedRotatingFileHandler(
            filename=error_log_file,
            when='midnight',
            interval=1,
            backupCount=90,  # 错误日志保留更久
            encoding='utf-8',
            delay=True
        )

        # 只记录错误和严重错误
        handler.setLevel(logging.ERROR)

        formatter = logging.Formatter(
            format_str,
            datefmt='%Y-%m-%d %H:%M:%S'
        )

        handler.setFormatter(formatter)
        handler.addFilter(RequestIDFilter())

        return handler

    except Exception as e:
        print(f"❌ 创建错误日志处理器失败: {e}")
        return None


def configure_loggers(settings: Settings) -> None:
    """配置特定的日志记录器 ⚙️"""

    # SQLAlchemy日志配置
    sqlalchemy_logger = logging.getLogger('sqlalchemy')
    if settings.DATABASE_ECHO:
        sqlalchemy_logger.setLevel(logging.INFO)
    else:
        sqlalchemy_logger.setLevel(logging.WARNING)
        sqlalchemy_logger.addFilter(SQLAlchemyFilter())

    # HTTP客户端日志
    urllib3_logger = logging.getLogger('urllib3')
    urllib3_logger.setLevel(logging.WARNING)

    # FastAPI日志配置
    uvicorn_logger = logging.getLogger('uvicorn')
    uvicorn_logger.setLevel(logging.INFO)

    # 自定义应用日志
    app_logger = logging.getLogger('backend')
    app_logger.setLevel(getattr(logging, settings.LOG_LEVEL.upper()))

    # 如果是生产环境，降低一些第三方库的日志级别
    if settings.is_production:
        noisy_loggers = [
            'urllib3.connectionpool',
            'requests.packages.urllib3',
            'asyncio',
            'concurrent.futures'
        ]

        for logger_name in noisy_loggers:
            logger = logging.getLogger(logger_name)
            logger.setLevel(logging.WARNING)


# ============= 核心日志获取函数 =============

def get_logger(name: str) -> logging.Logger:
    """获取日志记录器 📝

    Args:
        name: 日志记录器名称

    Returns:
        配置好的日志记录器
    """
    return logging.getLogger(name)


# ============= 安全日志系统 =============

class SecurityLogger:
    """安全事件日志记录器 🔒"""

    def __init__(self):
        self.logger = get_logger("security")

    def log_auth_attempt(self, username: str, ip_address: str, success: bool, **kwargs):
        """记录认证尝试"""
        status = "成功" if success else "失败"
        self.logger.info(
            f"🔐 认证{status}: 用户={username}, IP={ip_address}",
            extra={
                "event_type": "auth_attempt",
                "username": username,
                "ip_address": ip_address,
                "success": success,
                **kwargs
            }
        )

    def log_permission_denied(self, user_id: str, resource: str, action: str, **kwargs):
        """记录权限拒绝"""
        self.logger.warning(
            f"🚫 权限拒绝: 用户={user_id}, 资源={resource}, 操作={action}",
            extra={
                "event_type": "permission_denied",
                "user_id": user_id,
                "resource": resource,
                "action": action,
                **kwargs
            }
        )

    def log_suspicious_activity(self, description: str, **kwargs):
        """记录可疑活动"""
        self.logger.warning(
            f"⚠️ 可疑活动: {description}",
            extra={
                "event_type": "suspicious_activity",
                "description": description,
                **kwargs
            }
        )

    def log_data_access(self, user_id: str, data_type: str, operation: str, **kwargs):
        """记录数据访问"""
        self.logger.info(
            f"📊 数据访问: 用户={user_id}, 类型={data_type}, 操作={operation}",
            extra={
                "event_type": "data_access",
                "user_id": user_id,
                "data_type": data_type,
                "operation": operation,
                **kwargs
            }
        )

    def log_security_alert(self, alert_type: str, severity: str, description: str, **kwargs):
        """记录安全警报"""
        level = logging.CRITICAL if severity == "critical" else logging.WARNING

        self.logger.log(
            level,
            f"🚨 安全警报 [{severity.upper()}]: {alert_type} - {description}",
            extra={
                "event_type": "security_alert",
                "alert_type": alert_type,
                "severity": severity,
                "description": description,
                **kwargs
            }
        )


def get_security_logger() -> SecurityLogger:
    """获取安全日志记录器 🔒"""
    return SecurityLogger()


# ============= 性能监控日志系统 =============

class PerformanceLogger:
    """性能监控日志记录器 📊"""

    def __init__(self, name: str):
        self.logger = get_logger(f"performance.{name}")
        self.metrics = {}
        self.name = name

    def record_metric(self, name: str, value: float, unit: str = "", **kwargs):
        """记录性能指标"""
        self.metrics[name] = {"value": value, "unit": unit, **kwargs}
        self.logger.info(
            f"📊 {name}: {value}{unit}",
            extra={
                "event_type": "performance_metric",
                "metric_name": name,
                "metric_value": value,
                "metric_unit": unit,
                **kwargs
            }
        )

    def record_duration(self, name: str, duration: float, **kwargs):
        """记录执行时长"""
        self.record_metric(name, round(duration * 1000, 2), "ms", **kwargs)

    def record_counter(self, name: str, count: int, **kwargs):
        """记录计数器"""
        self.record_metric(name, count, "次", **kwargs)

    def record_memory_usage(self, name: str, memory_mb: float, **kwargs):
        """记录内存使用量"""
        self.record_metric(name, round(memory_mb, 2), "MB", **kwargs)

    def record_throughput(self, name: str, requests_per_second: float, **kwargs):
        """记录吞吐量"""
        self.record_metric(name, round(requests_per_second, 2), "req/s", **kwargs)

    def record_latency(self, name: str, latency_ms: float, percentile: str = None, **kwargs):
        """记录延迟"""
        metric_name = f"{name}_latency"
        if percentile:
            metric_name += f"_p{percentile}"

        self.record_metric(metric_name, round(latency_ms, 2), "ms", **kwargs)

    def record_error_rate(self, name: str, error_rate: float, **kwargs):
        """记录错误率"""
        self.record_metric(f"{name}_error_rate", round(error_rate * 100, 2), "%", **kwargs)

    def start_timer(self, name: str) -> 'TimerContext':
        """开始计时器"""
        return TimerContext(self, name)

    def flush_metrics(self):
        """输出所有指标汇总"""
        if self.metrics:
            self.logger.info(
                f"📈 性能指标汇总 [{self.name}]: {len(self.metrics)} 项指标",
                extra={
                    "event_type": "performance_summary",
                    "logger_name": self.name,
                    "metrics_count": len(self.metrics),
                    "metrics": self.metrics
                }
            )
            self.metrics.clear()


class TimerContext:
    """计时器上下文管理器 ⏱️"""

    def __init__(self, perf_logger: PerformanceLogger, name: str):
        self.perf_logger = perf_logger
        self.name = name
        self.start_time = None

    def __enter__(self):
        """开始计时"""
        import time
        self.start_time = time.time()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        """结束计时"""
        import time
        if self.start_time:
            duration = time.time() - self.start_time
            self.perf_logger.record_duration(self.name, duration)


def get_performance_logger(name: str) -> PerformanceLogger:
    """获取性能监控日志记录器 📊"""
    return PerformanceLogger(name)


# ============= 日志混入类 =============

class LoggerMixin:
    """日志记录器混入类 🔄"""

    @property
    def logger(self) -> logging.Logger:
        """获取当前类的日志记录器"""
        return get_logger(f"{self.__class__.__module__}.{self.__class__.__name__}")


# ============= 装饰器函数 =============

def log_execution_time(func_name: str = None):
    """记录函数执行时间装饰器 ⏱️"""

    def decorator(func):
        import functools
        import time

        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            name = func_name or f"{func.__module__}.{func.__name__}"
            logger = get_logger(name)

            start_time = time.time()
            try:
                result = func(*args, **kwargs)
                execution_time = time.time() - start_time
                logger.debug(f"⏱️ {name} 执行时间: {execution_time:.3f}s")
                return result
            except Exception as e:
                execution_time = time.time() - start_time
                logger.error(f"❌ {name} 执行失败 (时间: {execution_time:.3f}s): {e}")
                raise

        return wrapper

    return decorator


def log_async_execution_time(func_name: str = None):
    """记录异步函数执行时间装饰器 ⏱️"""

    def decorator(func):
        import functools
        import time

        @functools.wraps(func)
        async def wrapper(*args, **kwargs):
            name = func_name or f"{func.__module__}.{func.__name__}"
            logger = get_logger(name)

            start_time = time.time()
            try:
                result = await func(*args, **kwargs)
                execution_time = time.time() - start_time
                logger.debug(f"⏱️ {name} 执行时间: {execution_time:.3f}s")
                return result
            except Exception as e:
                execution_time = time.time() - start_time
                logger.error(f"❌ {name} 执行失败 (时间: {execution_time:.3f}s): {e}")
                raise

        return wrapper

    return decorator


# ============= 上下文日志记录器 =============

class ContextLogger:
    """上下文日志记录器 📋"""

    def __init__(self, logger: logging.Logger, **context):
        self.logger = logger
        self.context = context

    def _log(self, level: int, message: str, *args, **kwargs):
        """记录日志并添加上下文信息"""
        # 创建日志记录
        record = self.logger.makeRecord(
            self.logger.name, level, "", 0, message, args, None
        )

        # 添加上下文信息
        for key, value in self.context.items():
            setattr(record, key, value)

        # 添加额外的关键字参数
        for key, value in kwargs.items():
            setattr(record, key, value)

        self.logger.handle(record)

    def debug(self, message: str, *args, **kwargs):
        """记录调试日志"""
        self._log(logging.DEBUG, message, *args, **kwargs)

    def info(self, message: str, *args, **kwargs):
        """记录信息日志"""
        self._log(logging.INFO, message, *args, **kwargs)

    def warning(self, message: str, *args, **kwargs):
        """记录警告日志"""
        self._log(logging.WARNING, message, *args, **kwargs)

    def error(self, message: str, *args, **kwargs):
        """记录错误日志"""
        self._log(logging.ERROR, message, *args, **kwargs)

    def critical(self, message: str, *args, **kwargs):
        """记录严重错误日志"""
        self._log(logging.CRITICAL, message, *args, **kwargs)


def get_context_logger(name: str, **context) -> ContextLogger:
    """获取上下文日志记录器 📋

    Args:
        name: 日志记录器名称
        **context: 上下文信息

    Returns:
        上下文日志记录器
    """
    logger = get_logger(name)
    return ContextLogger(logger, **context)


# ============= 业务日志记录器 =============

class BusinessLogger:
    """业务事件日志记录器 💼"""

    def __init__(self):
        self.logger = get_logger("business")

    def log_user_registration(self, user_id: str, email: str, **kwargs):
        """记录用户注册"""
        self.logger.info(
            f"👤 用户注册: {user_id} ({email})",
            extra={
                "event_type": "user_registration",
                "user_id": user_id,
                "email": email,
                **kwargs
            }
        )

    def log_project_creation(self, user_id: str, project_id: str, project_name: str, **kwargs):
        """记录项目创建"""
        self.logger.info(
            f"📁 项目创建: {project_name} by {user_id}",
            extra={
                "event_type": "project_creation",
                "user_id": user_id,
                "project_id": project_id,
                "project_name": project_name,
                **kwargs
            }
        )

    def log_file_upload(self, user_id: str, file_name: str, file_size: int, **kwargs):
        """记录文件上传"""
        self.logger.info(
            f"📄 文件上传: {file_name} ({file_size} bytes) by {user_id}",
            extra={
                "event_type": "file_upload",
                "user_id": user_id,
                "file_name": file_name,
                "file_size": file_size,
                **kwargs
            }
        )

    def log_ai_interaction(self, user_id: str, model: str, tokens_used: int, **kwargs):
        """记录AI交互"""
        self.logger.info(
            f"🤖 AI交互: {model} ({tokens_used} tokens) by {user_id}",
            extra={
                "event_type": "ai_interaction",
                "user_id": user_id,
                "model": model,
                "tokens_used": tokens_used,
                **kwargs
            }
        )


def get_business_logger() -> BusinessLogger:
    """获取业务日志记录器 💼"""
    return BusinessLogger()


# ============= 系统监控日志记录器 =============

class SystemLogger:
    """系统监控日志记录器 ⚙️"""

    def __init__(self):
        self.logger = get_logger("system")

    def log_system_startup(self, version: str, environment: str, **kwargs):
        """记录系统启动"""
        self.logger.info(
            f"🚀 系统启动: v{version} ({environment})",
            extra={
                "event_type": "system_startup",
                "version": version,
                "environment": environment,
                **kwargs
            }
        )

    def log_system_shutdown(self, uptime_seconds: int, **kwargs):
        """记录系统关闭"""
        self.logger.info(
            f"🔒 系统关闭: 运行时间 {uptime_seconds}s",
            extra={
                "event_type": "system_shutdown",
                "uptime_seconds": uptime_seconds,
                **kwargs
            }
        )

    def log_database_migration(self, version: str, success: bool, **kwargs):
        """记录数据库迁移"""
        status = "成功" if success else "失败"
        level = logging.INFO if success else logging.ERROR

        self.logger.log(
            level,
            f"🗄️ 数据库迁移{status}: v{version}",
            extra={
                "event_type": "database_migration",
                "version": version,
                "success": success,
                **kwargs
            }
        )

    def log_resource_usage(self, cpu_percent: float, memory_mb: float, disk_gb: float, **kwargs):
        """记录资源使用情况"""
        self.logger.info(
            f"📊 资源使用: CPU {cpu_percent:.1f}%, 内存 {memory_mb:.1f}MB, 磁盘 {disk_gb:.1f}GB",
            extra={
                "event_type": "resource_usage",
                "cpu_percent": cpu_percent,
                "memory_mb": memory_mb,
                "disk_gb": disk_gb,
                **kwargs
            }
        )


def get_system_logger() -> SystemLogger:
    """获取系统监控日志记录器 ⚙️"""
    return SystemLogger()


# ============= 导出所有公共函数 =============

__all__ = [
    # 核心设置函数
    'setup_logging',

    # 获取日志记录器函数
    'get_logger',
    'get_security_logger',
    'get_performance_logger',
    'get_context_logger',
    'get_business_logger',
    'get_system_logger',

    # 日志记录器类
    'SecurityLogger',
    'PerformanceLogger',
    'ContextLogger',
    'BusinessLogger',
    'SystemLogger',

    # 混入类
    'LoggerMixin',

    # 装饰器
    'log_execution_time',
    'log_async_execution_time',

    # 工具类
    'TimerContext',
]

def log_function_call(logger_name: str = None, level: int = logging.INFO):
    """记录函数调用装饰器 📞"""

    def decorator(func: Callable) -> Callable:
        logger = get_logger(logger_name or func.__module__)

        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            # 记录函数调用
            args_repr = [repr(a) for a in args]
            kwargs_repr = [f"{k}={v!r}" for k, v in kwargs.items()]
            signature = ", ".join(args_repr + kwargs_repr)

            logger.log(level, f"📞 调用 {func.__name__}({signature})")

            try:
                result = func(*args, **kwargs)
                logger.log(level, f"✅ {func.__name__} 执行成功")
                return result
            except Exception as e:
                logger.error(f"❌ {func.__name__} 执行失败: {e}")
                raise

        @functools.wraps(func)
        async def async_wrapper(*args, **kwargs):
            # 记录异步函数调用
            args_repr = [repr(a) for a in args]
            kwargs_repr = [f"{k}={v!r}" for k, v in kwargs.items()]
            signature = ", ".join(args_repr + kwargs_repr)

            logger.log(level, f"📞 调用 {func.__name__}({signature})")

            try:
                result = await func(*args, **kwargs)
                logger.log(level, f"✅ {func.__name__} 执行成功")
                return result
            except Exception as e:
                logger.error(f"❌ {func.__name__} 执行失败: {e}")
                raise

        if asyncio.iscoroutinefunction(func):
            return async_wrapper
        else:
            return wrapper

    return decorator


def log_api_request(request_info: Dict[str, Any]):
    """记录API请求 🌐"""
    logger = get_logger("api")

    method = request_info.get("method", "UNKNOWN")
    path = request_info.get("path", "/")
    ip = request_info.get("client_ip", "unknown")
    user_agent = request_info.get("user_agent", "unknown")

    logger.info(
        f"🌐 API请求: {method} {path} from {ip}",
        extra={
            "event_type": "api_request",
            "method": method,
            "path": path,
            "client_ip": ip,
            "user_agent": user_agent,
            **request_info
        }
    )


def log_api_response(response_info: Dict[str, Any]):
    """记录API响应 📤"""
    logger = get_logger("api")

    status_code = response_info.get("status_code", 0)
    duration = response_info.get("duration", 0)
    path = response_info.get("path", "/")

    status_emoji = "✅" if 200 <= status_code < 300 else "⚠️" if 400 <= status_code < 500 else "❌"

    logger.info(
        f"{status_emoji} API响应: {status_code} {path} ({duration:.3f}s)",
        extra={
            "event_type": "api_response",
            "status_code": status_code,
            "duration": duration,
            "path": path,
            **response_info
        }
    )


def log_database_operation(operation: str, table: str, **kwargs):
    """记录数据库操作 🗄️"""
    logger = get_logger("database")

    logger.debug(
        f"🗄️ 数据库操作: {operation} on {table}",
        extra={
            "event_type": "database_operation",
            "operation": operation,
            "table": table,
            **kwargs
        }
    )


def log_security_event(event_type: str, description: str, **kwargs):
    """记录安全事件 🔒"""
    security_logger = get_security_logger()

    if event_type == "auth_attempt":
        security_logger.log_auth_attempt(**kwargs)
    elif event_type == "permission_denied":
        security_logger.log_permission_denied(**kwargs)
    elif event_type == "suspicious_activity":
        security_logger.log_suspicious_activity(description, **kwargs)
    else:
        security_logger.logger.warning(
            f"🔒 安全事件: {event_type} - {description}",
            extra={
                "event_type": event_type,
                "description": description,
                **kwargs
            }
        )


def log_performance_metric(name: str, value: float, unit: str = "", **kwargs):
    """记录性能指标 📊"""
    perf_logger = get_performance_logger("app")
    perf_logger.record_metric(name, value, unit)


def log_user_action(user_id: str, action: str, resource: str = None, **kwargs):
    """记录用户操作 👤"""
    logger = get_logger("user_actions")

    resource_str = f" on {resource}" if resource else ""

    logger.info(
        f"👤 用户操作: {user_id} {action}{resource_str}",
        extra={
            "event_type": "user_action",
            "user_id": user_id,
            "action": action,
            "resource": resource,
            "timestamp": datetime.utcnow().isoformat(),
            **kwargs
        }
    )


def log_system_event(event: str, level: int = logging.INFO, **kwargs):
    """记录系统事件 ⚙️"""
    logger = get_logger("system")

    logger.log(
        level,
        f"⚙️ 系统事件: {event}",
        extra={
            "event_type": "system_event",
            "event": event,
            **kwargs
        }
    )


def log_error_with_context(error: Exception, context: Dict[str, Any] = None):
    """记录带上下文的错误 ❌"""
    logger = get_logger("errors")

    context = context or {}

    logger.error(
        f"❌ 错误: {type(error).__name__}: {error}",
        exc_info=True,
        extra={
            "event_type": "error",
            "error_type": type(error).__name__,
            "error_message": str(error),
            **context
        }
    )


def log_cache_operation(operation: str, key: str, hit: bool = None, **kwargs):
    """记录缓存操作 💾"""
    logger = get_logger("cache")

    hit_status = " (HIT)" if hit is True else " (MISS)" if hit is False else ""

    logger.debug(
        f"💾 缓存操作: {operation} {key}{hit_status}",
        extra={
            "event_type": "cache_operation",
            "operation": operation,
            "key": key,
            "hit": hit,
            **kwargs
        }
    )


def log_file_operation(operation: str, file_path: str, **kwargs):
    """记录文件操作 📁"""
    logger = get_logger("files")

    logger.info(
        f"📁 文件操作: {operation} {file_path}",
        extra={
            "event_type": "file_operation",
            "operation": operation,
            "file_path": file_path,
            **kwargs
        }
    )


def log_ai_request(model: str, prompt_length: int, response_length: int = None, **kwargs):
    """记录AI请求 🤖"""
    logger = get_logger("ai")

    response_info = f", 响应长度: {response_length}" if response_length else ""

    logger.info(
        f"🤖 AI请求: 模型={model}, 提示长度={prompt_length}{response_info}",
        extra={
            "event_type": "ai_request",
            "model": model,
            "prompt_length": prompt_length,
            "response_length": response_length,
            **kwargs
        }
    )


class LogContext:
    """日志上下文管理器 📋"""

    def __init__(self, logger_name: str, **context):
        self.logger = get_logger(logger_name)
        self.context = context
        self.start_time = None

    def __enter__(self):
        """进入上下文"""
        import time
        self.start_time = time.time()

        context_str = ", ".join(f"{k}={v}" for k, v in self.context.items())
        self.logger.info(f"🔄 开始: {context_str}")

        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        """退出上下文"""
        import time
        duration = time.time() - self.start_time if self.start_time else 0

        if exc_type is None:
            self.logger.info(f"✅ 完成: 耗时 {duration:.3f}s")
        else:
            self.logger.error(f"❌ 异常: {exc_type.__name__}: {exc_val}, 耗时 {duration:.3f}s")

        return False  # 不抑制异常


def create_log_context(logger_name: str, **context) -> LogContext:
    """创建日志上下文 📋"""
    return LogContext(logger_name, **context)
